###############################################
# Build Stage
###############################################
FROM golang:1.25-alpine3.21 AS builder

# Labels for image identification
LABEL maintainer="UOS Libvirt Exporter Team"
LABEL description="Prometheus exporter for libvirt-based virtual machines"

# Configure USTC mirror for Alpine (Alpine 3.21)
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine/|https://mirrors.ustc.edu.cn/alpine/|g' /etc/apk/repositories

# Install build dependencies
RUN apk add --no-cache \
    git \
    make \
    gcc \
    musl-dev \
    libvirt-dev

# Set working directory
WORKDIR /build

# Copy go mod files
COPY go.mod go.sum ./

# Configure Go environment
RUN go env -w GO111MODULE=on
RUN go env -w GOPROXY=https://goproxy.cn,direct

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Get version from spec file and build the binary with version info
RUN VERSION=$(grep "^Version:" uos-libvirtd-exporter.spec | awk '{print $2}') && \
    CGO_ENABLED=1 GOOS=linux go build \
    -ldflags="-X gitee.com/openeuler/uos-libvirtd-exporter/version.Version=${VERSION} -s -w" \
    -o uos-libvirtd-exporter


###############################################
# Runtime Stage
###############################################
FROM alpine:latest

# Labels for image identification
LABEL maintainer="UOS Libvirt Exporter Team"
LABEL description="Prometheus exporter for libvirt-based virtual machines"
LABEL name="uos-libvirtd-exporter"

# Configure USTC mirror for Alpine (alpine:latest)
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine/|https://mirrors.ustc.edu.cn/alpine/|g' /etc/apk/repositories

# Install runtime dependencies
RUN apk add --no-cache \
    libvirt-client \
    openssh-client \
    iputils \
    curl \
    net-tools \
    wget

# Create directories
RUN mkdir -p /etc/uos-libvirtd-exporter && \
    mkdir -p /var/log/uos-libvirtd-exporter

# Copy binary from builder stage
COPY --from=builder /build/uos-libvirtd-exporter /usr/bin/uos-libvirtd-exporter

# Copy configuration files
COPY --from=builder /build/config.yaml /etc/uos-libvirtd-exporter/config.yaml
COPY --from=builder /build/quickstart/entrypoint.sh /entrypoint.sh

# Set permissions
RUN chmod +x /entrypoint.sh

# Expose metrics port
EXPOSE 9177

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:9177/ || exit 1

# Run the exporter
ENTRYPOINT ["/entrypoint.sh"]